package com.defysoft.waukidsbus.end;

import java.util.ArrayList;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukidsbus.BaseActivity;
import com.defysoft.waukidsbus.Data_Type.EndBus;
import com.defysoft.waukidsbus.JsonParser;
import com.defysoft.waukidsbus.R;
import com.defysoft.waukidsbus.Sqlite_Connect;

public class End_ScanMode extends BaseActivity implements OnClickListener {
	Toolbar toolbar;

	private BluetoothAdapter mBluetoothAdapter;
	private static final int REQUEST_ENABLE_BT = 3;

	TextView rescan;
	private Handler mHandler;

	final int SUCCESS = 10;
	final int SUBSUCCESS = 9;
	final int STARTBUS = 7;
	final int FAIR = 8;
	final int THREESUCCESS = 6;
	int checkmode = 0;
	int checksu = 3; // 귀가 체크횟수
	GridView gridView;
	RelativeLayout start, stop;
	boolean onoff = true;
	ArrayList<EndBus> list;
	ArrayList<String> getuuid;
	String endcode = null;
	String sendcode = null;
	private long SCAN_PERIOD = 10000;
	Sqlite_Connect sc;
	RelativeLayout RL;
	TextView err;
	TextView normal;
	TextView close;
	ListView log;
	int scancount = 0;
	LogAdapter logAdapter;
	ArrayList<String> loglist;
	Cursor cursor;
	Cursor savelog;
	private SharedPreferences login_code;
	String code;
	EndAdapter endAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_end__scan_mode);
		startDIal();
		setStartData();
		setstartLog();

	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {// ���������������üũ

		switch (requestCode) {
		case REQUEST_ENABLE_BT:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) { // ������� ������
				// Bluetooth is now enabled, so set up a chat session
				Toast.makeText(this, "블루투스 사용가능", Toast.LENGTH_LONG).show();
				startThread(1);
			} else { // ������� ������ ���� �����佺Ʈ ���� ��
				// User did not enable Bluetooth or an error occurred
				Toast.makeText(this, "블루투스 사용불가", Toast.LENGTH_LONG).show();
				finish();
			}
		}
	}

	public void setstartLog() {
		RL = (RelativeLayout) findViewById(R.id.END_SCAN_RL);
		err = (TextView) findViewById(R.id.END_SCAN_LOG_ERR);
		log = (ListView) findViewById(R.id.END_SCAN_LOG);
		loglist = new ArrayList<String>();
		logAdapter = new LogAdapter();
		log.setAdapter(logAdapter);
		normal = (TextView) findViewById(R.id.END_SCAN_LOG_NORMAR);
		close = (TextView) findViewById(R.id.END_SCAN_LOG_EXIT);
		normal.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				loglist = new ArrayList<String>();
				if (cursor != null) {
					cursor.close();
				}
				cursor = sc.check_BACK_BUS();
				while (cursor.moveToNext()) {
					loglist.add(cursor.getString(0) + cursor.getInt(2)
							+ (cursor.getInt(2) % 2 == 1 ? "  # " : "  @ ")
							+ cursor.getString(1));
				}
				logAdapter.notifyDataSetChanged();
				RL.setVisibility(View.VISIBLE);
			}
		});
		err.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				loglist = new ArrayList<String>();
				if (cursor != null) {
					cursor.close();
				}
				cursor = sc.check_BACK_BUS(1);
				while (cursor.moveToNext()) {
					loglist.add(cursor.getString(0) + "  # "
							+ cursor.getString(1));
				}
				logAdapter.notifyDataSetChanged();
				RL.setVisibility(View.VISIBLE);
			}
		});
		close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				RL.setVisibility(View.GONE);
			}
		});
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		if (checkmode == 0) {
			stop.callOnClick();
		} else {
			super.finish();
			checkScanLeDevice(false);
		}
	}

	@Override
	public void setStartData() {
		// TODO Auto-generated method stub
		super.setStartData();
		try {
			SCAN_PERIOD = (Integer.parseInt(getIntent()
					.getStringExtra("second")) * 1000);
		} catch (Exception e) {
			SCAN_PERIOD = 1000;
		}
		sc = new Sqlite_Connect(this);
		mHandler = new Handler();
		rescan = (TextView) findViewById(R.id.END_SCAN_RESCAN);
		rescan.setOnClickListener(this);
		start = (RelativeLayout) findViewById(R.id.END_SCAN_START);
		start.setOnClickListener(this);
		code = getIntent().getStringExtra("code");
		stop = (RelativeLayout) findViewById(R.id.END_SCAN_STOP);
		gridView = (GridView) findViewById(R.id.END_SCAN_GRID);
		login_code = getSharedPreferences("login_code", MODE_PRIVATE);
		toolbar = (Toolbar) findViewById(R.id.END_SCAN_TOOL);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		stop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(
						End_ScanMode.this);
				builder.setMessage(
						login_code.getString("sch_name", "") + " 버스의 운행을 종료합니다")
						.setCancelable(false)
						.setPositiveButton("종료",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										checkmode = 1;
										checkScanLeDevice(false);
										finish();
									}
								})
						.setNegativeButton("취소",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();
			}
		});
		final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = bluetoothManager.getAdapter();
		if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		} else {
			startThread(1);
		}
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				switch (cho) {
				case 1:
					mainThread();
					break;
				case 2:
					subThread();
					break;
				case 3:
					threeThread();
					break;
				}
			}
		});
		firstThread.start();
	}

	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			break;
		case FAIR:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;
		case SUCCESS:
			if (firstThread == null) {
				firstThread.interrupt();
			}
			list = JsonParser.EndScanMode((String) _message.obj);
			if (list == null) {
				endDIal();
				Toast.makeText(this, "노선에 등록된 원생이 없습니다.", Toast.LENGTH_SHORT)
						.show();
				finish();
			} else if (list.size() == 0) {
				endDIal();
				Toast.makeText(this, "노선에 등록된 원생이 없습니다.", Toast.LENGTH_SHORT)
						.show();
				finish();
			} else {
				endDIal();
				endAdapter = new EndAdapter();
				gridView.setAdapter(endAdapter);
				scanLeDevice(true);
			}
			break;
		case STARTBUS:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			break;

		case SUBSUCCESS:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			sc.insert_BACK_BUS("귀가버스 스캔정상시작", 2);
			checkScanLeDevice(onoff);
			break;
		case THREESUCCESS:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			if (_message.obj.equals("aset")) {
				Toast.makeText(this, "네트워크 상태를 확인하세요", Toast.LENGTH_SHORT)
						.show();
			}
			checkScanLeDevice(onoff);

			break;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.END_SCAN_RESCAN:

			scanLeDevice(true);
			break;
		case R.id.END_SCAN_START:
			AlertDialog.Builder builder = new AlertDialog.Builder(
					End_ScanMode.this);
			builder.setMessage(
					login_code.getString("sch_name", "유치원")
							+ " 버스의 운행을 시작합니다. \n운행이 시작되면 부모님께 메시지가 전송 됩니다.")
					.setCancelable(false)
					.setPositiveButton("운행시작",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									clickBtn();
									startDIal();
									startThread(2);
								}
							})
					.setNegativeButton("취소",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
			break;
		}
	}

	private void clickBtn() {
		rescan.setVisibility(View.INVISIBLE);
		start.setVisibility(View.INVISIBLE);
		rescan.setOnClickListener(null);
		start.setOnClickListener(null);
	}

	private void scanLeDevice(final boolean enable) {
		startDIal();
		if (enable) {
			getuuid = new ArrayList<String>();
			// Stops scanning after a pre-defined scan period.
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
					for (int i = 0; i < list.size(); i++) {
						list.get(i).checkon = checksu;
					}
					for (int i = 0; i < list.size(); i++) {
						for (int j = 0; j < getuuid.size(); j++) {
							if (list.get(i).bea_id.equals(getuuid.get(j))) {
								list.get(i).checkon = 0;
									sc.insert_BACK_BUS(list.get(i).stu_name
											+ "의 비콘의 신호를 인식했습니다. "+list.get(i).rssi, 2);
								
								break;
							}
						}
					}
					endAdapter.notifyDataSetChanged();

					endDIal();
				}
			}, SCAN_PERIOD);
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}
	}

	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		@Override
		public void onLeScan(final BluetoothDevice device, int rssi,
				byte[] scanRecord) {
			final int rss = rssi;
			final byte[] scan = scanRecord;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					boolean addcheck = true;
					String uuid = device.getAddress();
					for (int i = 0; i < getuuid.size(); i++) {
						if (getuuid.get(i).equals(uuid)) {
							addcheck = false;
							
						}
					}
					if (addcheck) {
						getuuid.add(uuid);
					}
					for (int i = 0; i < list.size(); i++) {
						if (uuid.equals(list.get(i).bea_id)) {
							list.get(i).rssi = rss + "";
							
						}
					}
				}
			});
		}
	};

	private void checkScanLeDevice(final boolean enable) {
		if (enable) {
			getuuid = new ArrayList<String>();
			// Stops scanning after a pre-defined scan period.
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
					Toast.makeText(End_ScanMode.this, "Search",
							Toast.LENGTH_SHORT).show();

					boolean havecheck;
					for (int i = 0; i < list.size(); i++) {
						if (list.get(i).checkon < checksu) {
							havecheck = true;
							for (int j = 0; j < getuuid.size(); j++) {
								if (list.get(i).bea_id.equals(getuuid.get(j))) {
									if (list.get(i).checkon != 0) {
										sc.insert_BACK_BUS(list.get(i).stu_name
												+ "의 비콘의 신호를 다시 인식했습니다. "+list.get(i).rssi, 2);
									}
									list.get(i).checkon = 0;
									Log.i("aad", list.get(i).bea_id);
									havecheck = false;
									break;
								}
							}
							if (havecheck == true
									&& list.get(i).checkon < checksu) {
								list.get(i).checkon++;

								if (list.get(i).checkon == checksu) {
									sc.insert_BACK_BUS(list.get(i).stu_name
											+ "이 하차처리되었습니다. 마지막rssi값"+list.get(i).rssi, 2);
									if (endcode == null) {
										endcode = list.get(i).stu_code;
									} else {
										endcode += "-" + list.get(i).stu_code;
									}
								} else {
									sc.insert_BACK_BUS(list.get(i).stu_name
											+ "의 비콘이 인식되지 않습니다. "
											+ (checksu - list.get(i).checkon)+" "
											+ "번 더 인식되지 않으면 하차처리됩니다. 마지막rssi값"+list.get(i).rssi, 2);
								}
							}

						}
					}
					endAdapter.notifyDataSetChanged();

					startThread(3);

				}
			}, SCAN_PERIOD);
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			onoff = false;
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}
	}

	class EndAdapter extends ArrayAdapter<String> {

		public EndAdapter() {
			super(End_ScanMode.this, 0);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			EndHolder startHolder;
			if (convertView == null) {
				startHolder = new EndHolder();
				convertView = getLayoutInflater().inflate(
						R.layout.start_scanmode_row, null);
				int width = ((gridView.getWidth()) / 5);
				int height = ((gridView.getWidth()) / 5);
				startHolder.ll = (LinearLayout) convertView
						.findViewById(R.id.START_SCANMODE_LL);
				startHolder.ll.setLayoutParams(new LinearLayout.LayoutParams(
						width, height));

				startHolder.textView = (TextView) convertView
						.findViewById(R.id.START_SCANMODE_ROW);
				convertView.setTag(startHolder);
			} else {
				startHolder = (EndHolder) convertView.getTag();
			}
			startHolder.textView.setText(list.get(position).stu_name+" "
					+ list.get(position).rssi);
			if (list.get(position).checkon < checksu) {
				startHolder.ll
						.setBackgroundResource(R.drawable.selectitem_blue_on);
			} else {
				startHolder.ll
						.setBackgroundResource(R.drawable.selectitem_blue_off);
			}

			return convertView;
		}
	}

	private void mainThread() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_SCANMODEEND, "code=" + code));
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				onNetworkCallback(SUCCESS, msg);
			} else {
				onNetworkCallback(FAIR, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString());
		}
		;
	}

	private void subThread() {
		String msg = "";
		sendcode = null;

		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).checkon == 0) {
				if (sendcode == null) {
					sendcode = list.get(i).stu_code;
				} else {
					sendcode += "-" + list.get(i).stu_code;
				}
			}
		}
		try {
			if (sendcode != null) {
				JSONObject jsonObject = new JSONObject(publicHttpCallback(
						HTTP_SENDENDGCM, "code=" + sendcode+"&sth="+login_code.getString("sch_code",null)+"&subcode="+code));
			}
			onNetworkCallback(SUBSUCCESS, msg);

		} catch (Exception e) {
			onNetworkCallback(SUBSUCCESS, e.toString());
		}
		;
	}

	private void threeThread() {
		String msg = "";
		sendcode = null;
		scancount++;
		Log.i("통신전", "통신전");
		try {
			if (isNetworkStat(this)) {
				if (scancount % 5 == 0) {
					Log.i("통신전1", "통신전1");
					if ((savelog = sc.save_BACK_BUS()).getCount() > 0) {
						Log.i("통신전2", "통신전2");
						String logstr = null;
						while (savelog.moveToNext()) {
							if (logstr == null) {
								logstr = savelog.getString(0) + "::"
										+ savelog.getString(1) + "::"
										+ savelog.getString(2);
							} else {
								logstr += "," + savelog.getString(0) + "::"
										+ savelog.getString(1) + "::"
										+ savelog.getString(2);
							}

						}
						Log.i("통신전3", "통신전3");
						JSONObject jsonObjecta = new JSONObject(
								publicHttpCallback(
										HTTP_SENDENDLOG,
										"code="
												+ logstr
												+ "&sch="
												+ login_code.getString(
														"sch_code", null)));
						Log.i("통신후", "통신후");
						if (jsonObjecta.getBoolean("success")) {
							Log.i("통신성공", "통신성고");
							sc.update_BACK_BUS();

						}
					}
				}
				if (endcode != null) {
					JSONObject jsonObject = new JSONObject(publicHttpCallback(
							HTTP_INSERT_END, "code=" + endcode));
					String[] checkon = endcode.split("-");
					for (int i = 0; i < checkon.length; i++) {
						for (int j = 0; j < list.size(); j++) {
							if (list.get(j).stu_code.equals(checkon[i])) {
								sc.insert_BACK_BUS(list.get(j).stu_name
										+ "이 하차처리결과 서버에 전송 및 푸시발송 되었습니다.", 2);
								break;
							}
						}
					}
					endcode = null;
				}
				onNetworkCallback(THREESUCCESS, msg);
			} else {
				sc.insert_BACK_BUS("네트워크상태 통신 불가 와이파이연결 안됨", 3);
				onNetworkCallback(THREESUCCESS, "aset");
			}
		} catch (Exception e) {
			onNetworkCallback(THREESUCCESS, e.toString());
			sc.insert_BACK_BUS("서버통신오류(서버문제)" + e.toString(), 3);
		}
		;
	}

	class EndHolder {
		TextView textView;
		LinearLayout ll;
	}

	class LogAdapter extends ArrayAdapter<String> {

		public LogAdapter() {
			super(End_ScanMode.this, 0);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return loglist.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			TextView tv;
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(R.layout.logitem,
						null);
				tv = (TextView) convertView.findViewById(R.id.logitem_tv);
				convertView.setTag(tv);
			} else {
				tv = (TextView) convertView.getTag();
			}
			tv.setText(loglist.get(position));
			return convertView;
		}

	}
}
